package edu.java.ishop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

import edu.java.ishop.dao.ProductDao;
import edu.java.ishop.model.Product;
import edu.java.ishop.model.ProductCategory;

@Named("database")
public class ProductDatabaseDao  implements
		ProductDao {

	@Inject
	private DataSource dataSource;
	
	public ProductDatabaseDao() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Product> getAll() {
		List<Product> result = new ArrayList<>();
		try (Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn
						.prepareStatement("select * from product");
				//.prepareStatement("select p.id, p.name, p.price, p.description, pc.id, pc.name from product p, productCategory pc where p.categoryId = pc.id");
				ResultSet rs = pstmt.executeQuery()) {
			while (rs.next()) {
				Product p = new Product();
				p.setId(rs.getLong(1));
				p.setName(rs.getString(2));
				p.setPrice(rs.getBigDecimal(3));
				p.setDescription(rs.getString(4));
				p.setCategory(new ProductCategory(rs.getLong(5)));
				// TODO: refactor->add join to productcategory
				//p.setCategory(new ProductCategory(rs.getLong(5), rs.getString(6)));
				result.add(p);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return result;
	}

	@Override
	public Product getById(long Id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void save(Product item) {
		try (Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn
						.prepareStatement("insert into product(name,price,description,categoryId) values(?,?,?,?)");) {
			pstmt.setString(1, item.getName());
			pstmt.setBigDecimal(2, item.getPrice());
			pstmt.setString(3, item.getDescription());
			pstmt.setLong(4, item.getCategory().getId());
			pstmt.execute();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void delete(Product item) {
		try(Connection connection = dataSource.getConnection();
				PreparedStatement pstmt = connection.prepareStatement("delete from product where id = ?");){
			pstmt.setLong(1,item.getId());
			pstmt.execute();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public Product getByCategory(ProductCategory category) {
		// TODO Auto-generated method stub
		return null;
	}



}
